﻿//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Justin Wallace Saunders">
//     Copyright (c) Microsoft Public License. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Community.Tools.Windows.Service
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.ServiceProcess;
    
    /// <summary>
    /// Program class.
    /// </summary>
    public static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        /// <param name="args">Command-line arguments</param>
        public static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            var dictionary = new Dictionary<string, string>();
            var settings = new Settings();
            if (args.Length > 0)
            {
                foreach (string token in args)
                {
                    if (token.StartsWith("-", StringComparison.Ordinal)
                        || token.StartsWith("/", StringComparison.Ordinal))
                    {
                        var tokens = token.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                        if (tokens.Length != 2)
                        {
                            throw new ArgumentException("Invalid argument provided");
                        }

                        string identifier = tokens[0].TrimStart(new[] { '-', '/' });
                        string value = tokens[1];
                        settings.Dictionary.Add(identifier, value);
                    }
                }
            }

            foreach (var pair in settings.Dictionary)
            {
                if (pair.Key == "ELN")
                {
                    settings.EventLogName = pair.Value;
                }
                else if (pair.Key == "ELSN")
                {
                    settings.EventLogSourceName = pair.Value;
                }
                else if (pair.Key == "SPL")
                {
                    settings.ServicePollingInterval = long.Parse(pair.Value, CultureInfo.CurrentCulture);
                }
                else if (pair.Key == "PD")
                {
                    settings.PluginDirectory = pair.Value;
                }
                else if (pair.Key == "TTL")
                {
                    settings.TimetoLiveInterval = long.Parse(pair.Value, CultureInfo.CurrentCulture); 
                }
            }

            ServiceBase[] servicesToRun;
            servicesToRun = new ServiceBase[] { new Service(settings) };
            ServiceBase.Run(servicesToRun);
        }
    }
}
